﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using EasyBlog.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace EasyBlog.Controllers
{
    public class AccountController : Controller
    {
        private readonly DbXlp db;
        public AccountController(DbXlp dbxlp)
        {
            db = dbxlp;
        }
        public IActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public IActionResult CheckUserName(string userName)
        {
            if (db.InfoUsers.Any(ii => ii.UserName == userName))
                return Json(new { message = 1 });
            else
                return Json(new { message = 0 });

        }

        [HttpPost]
        public IActionResult Save(string userName, string password)
        {
            try
            {
                InfoUser item = new InfoUser { UserName = userName, Password = password, DTCreate = DateTime.Now };
                db.InfoUsers.Add(item);
                db.SaveChanges();
                return Json(new { message = "保存成功！" });

            }
            catch (Exception ex)
            {
                return Json(new { message = $"保存失败，原因：{ex.Message},{ex.InnerException}" });

            }


        }


        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        [ActionName("Login")]
        public async Task<ActionResult> Logining()
        {
            var userName = Request.Form["UserName"];
            var password = Request.Form["Password"];
            var item = db.InfoUsers.Find(userName);

            if (item != null && password == item.Password)
            {

                item.DTLogin = DateTime.Now;
                db.SaveChanges();


                var claims = new List<Claim>();

                claims.Add(new Claim(ClaimTypes.Name, userName));

                var claimsIdentity = new ClaimsIdentity(claims, "Cookies");
                await HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity));
                return RedirectToAction("Index", "Blog");
            }
            else
                ViewBag.Msg = "登陆失败";
            return View();
        }

        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync("Cookies");
            return RedirectToAction("Index", "Home");

        }

        public ActionResult EchartsInfo()
        {
            return View();
        }
        [HttpPost]
        [ActionName("EchartsInfo")]
        public ActionResult GetData()
        {
            //string name;
            //int count;
            var items = db.InfoBlogs.GroupBy(x => x.UserName).Select(g => (new { name = g.Key, count = g.Count() }));
            string json = JsonConvert.SerializeObject(items);
            return Content(json);
        }

        public ActionResult SetHeaderImg()
        {
            return View();
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns>上传文件结果信息</returns>
        [HttpPost]
        [ActionName("SetHeaderImg")]
        public async Task<ActionResult> UploadFile()
        {
            var file = Request.Form.Files["myFile"];
            if (file != null)
            {
                using MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                var item = db.InfoUsers.Find(User.Identity.Name);
                item.HeaderImg = ms.ToArray();
                await db.SaveChangesAsync();
                ViewBag.Msg = "上传成功";
                return View();
            }
            else
            {
                return Content("没有文件需要上传！");
            }
        }



        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public IActionResult CheckPassWord(string userName, string passWord)
        {
        
                var item = db.InfoUsers.Find(userName);
                if (item.Password != passWord)
                    return Json(new { message = 1 });
                else
                    return Json(new { message = 0 });
         
        }

        [HttpPost]
        [ActionName("ChangePassword")]
        public async Task<ActionResult> ChangePasswording(string userName, string passWord)
        {
            try
            {
                var item = db.InfoUsers.Find(userName);
                item.Password = passWord;
                await db.SaveChangesAsync();
                await HttpContext.SignOutAsync("Cookies");
                return Json(new { message = 0});

            }
            catch (Exception ex)
            {

                return Json(new { message = $"修改失败，原因：{ex.Message},{ex.InnerException}" });
            }

        }
    }
}